<template>
  <div id="test-container">
    <h3>markdown使用示例</h3>
    <el-button type="success" @click="getContent">获取内容</el-button>
    <el-button type="success" @click="insertContent">插入内容</el-button>
    <el-button type="success" @click="setContent">设置内容（覆盖）</el-button>

    <!-- markdown内容容器 -->
    <div id="test-markdown"></div>
  </div>
</template>

<script setup lang="ts">
import { Storage } from "@/utils/storage";
import { ACCESS_TOKEN_KEY } from "@/constants/cache-keys";

import Vditor from 'vditor'
// 导入样式
import "../../../node_modules/vditor/src/assets/less/index.less"

const vditor = ref<Vditor | null>(null)

onMounted(() => {
  // 初始化富文本编辑器
  vditor.value = new Vditor('test-markdown', {
    // toolbar: ['emoji', 'bold', '|', 'line'],
    toolbarConfig: {
      hide: false,
      pin: true
    },
    outline: {
      enable: true,
      position: 'right'
    },
    cache: {
      enable: true,
      after(html: string) {
        console.log('after=>', html)

        // nextTick(() => {
        //   // 固定定位大纲位置
        //   let outLineEle = document.querySelector('.vditor-outline')
        //   outLineEle.style.position = 'fixed'
        //   outLineEle.style.right = '10px'
        // })



      }
    },
    upload: {
      url: 'http://127.0.0.1:4000/api/admin/upload',
      fieldName: 'avatar',
      accept: 'image/*',
      // 上传成功的回调
      success(editor: HTMLPreElement, msg: string) {
        let result = JSON.parse(msg)
        let photoUrl = result.data.server_url + result.data.path
        if (vditor.value) {
          // 插入光标位置
          vditor.value.insertValue(`![](${photoUrl})`)
        }

      },
      headers: {
        // JWT token
        Authorization: Storage.get(ACCESS_TOKEN_KEY)
      }
    }
  })
})


const getContent = () => {
  if (vditor.value) {
    // console.log(vditor.value.getValue()) // 获取markdown源代码格式
    console.log(vditor.value.getHTML()) // 获取html源代码格式
  }
}

const insertContent = () => {
  if (vditor.value) {
    // vditor.value.insertValue('## 我是二级标题')
    vditor.value.insertValue('![这是我兄弟](http://gips2.baidu.com/it/u=195724436,3554684702&fm=3028&app=3028&f=JPEG&fmt=auto?w=1280&h=960)')
  }
}

const setContent = () => {
  if (vditor.value) {
    // vditor.value.setValue('# es6') // 覆盖式
    // vditor.value.blur()
    // console.log(vditor.value.getSelection())
    // vditor.value.disabled()

  }
}

</script>

<style scoped></style>
